package com.example.demo.controller;

import com.example.demo.entity.MbtiQuestion;
import com.example.demo.repository.MbtiQuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * MBTI题库管理控制器：查询全部、按ID查询、添加、修改、删除题目
 */
@RestController
@RequestMapping("/api/questions")
@CrossOrigin
public class MbtiQuestionController {

    @Autowired
    private MbtiQuestionRepository questionRepository;

    /**
     * 获取全部题目
     */
    @GetMapping
    public List<MbtiQuestion> getAllQuestions() {
        return questionRepository.findAll();
    }

    /**
     * 根据ID获取单个题目
     */
    @GetMapping("/{id}")
    public MbtiQuestion getQuestionById(@PathVariable Long id) {
        return questionRepository.findById(id).orElse(null);
    }

    /**
     * 添加新题目
     */
    @PostMapping
    public MbtiQuestion createQuestion(@RequestBody MbtiQuestion question) {
        return questionRepository.save(question);
    }

    /**
     * 修改已有题目
     */
    @PutMapping("/{id}")
    public MbtiQuestion updateQuestion(@PathVariable Long id, @RequestBody MbtiQuestion updatedQuestion) {
        Optional<MbtiQuestion> optional = questionRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        MbtiQuestion question = optional.get();
        question.setText(updatedQuestion.getText());
        question.setOptionA(updatedQuestion.getOptionA());
        question.setOptionB(updatedQuestion.getOptionB());
        question.setDimension(updatedQuestion.getDimension());
        question.setDirection(updatedQuestion.getDirection());

        return questionRepository.save(question);
    }

    /**
     * 删除题目
     */
    @DeleteMapping("/{id}")
    public void deleteQuestion(@PathVariable Long id) {
        questionRepository.deleteById(id);
    }
}
